package com.example.netty.pipeline;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Date;

/**
 * @author liupk
 * @date 2018/10/23
 */
public class NettyClient {
    
    public static void main(String[] args) throws InterruptedException {
        /**创建引导类 注意 客户端引导类和服务端引导类不同*/
        Bootstrap bootstrap = new Bootstrap();
        /**创建数据处理组*/
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        bootstrap
                .group(eventExecutors)
                /**服务端是NioServerSocketChannel*/
                .channel(NioSocketChannel.class)
                /**添加handle处理器，这里用了调用链模式*/
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        /**添加解码器*/
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });
        /**连接服务端并且返回服务端会话*/
        Channel channel = bootstrap.connect("127.0.0.1", 8002).channel();
        
        /**写个死循环，隔一段时间给服务端发消息*/
        while (true){
            channel.writeAndFlush(new Date()+"hello netty");
            Thread.sleep(2000);
        }
    }
}